package com.xiaoyuan.minicore.dao;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;

import com.xiaoyuan.minicore.core.ConfigHelper;
import com.xiaoyuan.minicore.orm.EntityHelper;
import com.xiaoyuan.minicore.util.DBUtil;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;

/**
 * @Auther: xiaoyuan
 * @Date: 2020/4/28
 * @Description:
 */
public class DBHelper {

    private static final BasicDataSource ds = new BasicDataSource();
    private static final QueryRunner runner = new QueryRunner(ds);

    // 定义一个局部线程变量（使每个线程都拥有自己的连接）
    private static ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>();

    // 当前线程进入事务次数
    private static ThreadLocal<Integer> inTransactionNum = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    static {
        ds.setDriverClassName(ConfigHelper.getString("jdbc.driver"));
        ds.setUrl(ConfigHelper.getString("jdbc.url"));
        ds.setUsername(ConfigHelper.getString("jdbc.username"));
        ds.setPassword(ConfigHelper.getString("jdbc.password"));
        ds.setMaxActive(Integer.parseInt(ConfigHelper.getString("jdbc.max.active")));
    }

    // 获取数据源
    public static DataSource getDataSource() {
        return ds;
    }


    // 开启事务
    public static void beginTransaction() {
        Connection conn = connContainer.get();
        inTransactionNum.set(inTransactionNum.get() + 1);
        if (conn == null) {
            try {
                conn = ds.getConnection();
                conn.setAutoCommit(false);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connContainer.set(conn);
            }
        }
    }

    // 提交事务
    public static void commitTransaction() {
        inTransactionNum.set(inTransactionNum.get() - 1);
        if (inTransactionNum.get() > 0) {
            return;
        }
        Connection conn = connContainer.get();
        if (conn != null) {
            try {
                conn.commit();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connContainer.remove();
            }
        }
    }

    // 回滚事务
    public static void rollbackTransaction() {
        Connection conn = connContainer.get();
        if (conn != null) {
            try {
                conn.rollback();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connContainer.remove();
            }
        }
    }

    // 执行查询语句（返回一个对象）
    public static <T> T queryBean(Class<T> cls, String sql, Object... params) {
        Map<String, String> map = EntityHelper.getEntityMap().get(cls);
        return DBUtil.queryBean(runner, cls, map, sql, params);
    }

    // 执行查询语句（返回多个对象）
    public static <T> List<T> queryBeanList(Class<T> cls, String sql, Object... params) {
        Map<String, String> map = EntityHelper.getEntityMap().get(cls);
        return DBUtil.queryBeanList(runner, cls, map, sql, params);
    }

    // 执行更新语句（包括 UPDATE、INSERT、DELETE）
    public static int update(String sql, Object... params) {
        return DBUtil.update(runner, connContainer.get(), sql, params);
    }

}
